package test1;

import java.sql.*;
import java.util.ArrayList;

public class Test3 {
    static {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    private static String url = "jdbc:mysql://localhost:3306/test";
    private static String user = "root";
    private static String password = "bawan114";

    public static void main(String[] args) {
        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;
        try {
            connection = DriverManager.getConnection(url, user, password);
            statement = connection.createStatement();
            String sql = "select * from t_student";
            resultSet = statement.executeQuery(sql);
            ArrayList<Student> list=new ArrayList<>();
            while(resultSet.next()){
                String id = resultSet.getString("id");
                String name = resultSet.getString("name");
                int age = resultSet.getInt("age");
                Student s=new Student();
                s.setId(id);
                s.setName(name);
                s.setAge(age);
                list.add(s);
            }

            for (Student s:list
                 ) {
                System.out.println(s);
            }

        } catch (Exception e) {
           e.printStackTrace();
        } finally {
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
            if (statement != null) {
                try {
                    statement.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
            if (resultSet != null) {
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
